[% setvar title Subroutines : Pre- and post- handlers for subroutines %]
<div id="archive-notice">
    <h3>This file is part of the Perl 6 Archive</h3>
    <p>To see what is currently happening visit <a href="http://www.perl6.org/">http://www.perl6.org/</a></p>
</div>
<div class='pod'>
<a name='TITLE'></a><h1>TITLE</h1>
<p>Subroutines : Pre- and post- handlers for subroutines</p>
<a name='VERSION'></a><h1>VERSION</h1>
<pre>  Maintainer: Damian Conway &lt;<a href='mailto:damian@conway.org'>damian@conway.org</a>&gt;
  Date: 20 Sep 2000
  Last Modified: 29 Sep 2000
  Mailing List: <a href='mailto:perl6-language@perl.org'>perl6-language@perl.org</a>
  Number: 271
  Version: 3
  Status: Frozen
  Frozen since: v2</pre>
<a name='ABSTRACT'></a><h1>ABSTRACT</h1>
<p>In response to the desiderata set out in RFC 194 and in the
Class::Contract module, this RFC proposes a generic &quot;handler&quot; mechanism
that can install behaviours around (before or after) a subroutine invocation.</p>
<a name='DESCRIPTION'></a><h1>DESCRIPTION</h1>
<a name='Overall semantics'></a><h2>Overall semantics</h2>
<p>It is proposed to provide a mechanism which allows two sequences of
&quot;handlers&quot; to be associated with a specific subroutine or built-in
function (hereafter referred to as the <i>primary</i>).</p>
<p>One sequence of handlers (the <i>prefix sequence</i>) would be called
whenever the primary is invoked, but <i>before</i> the body of the primary
is executed. Each handler would itself be a subroutine, and each would
be called with the argument list being passed to the primary it prefixes,
plus an extra argument (specifically, $_[-1]) representing a slot for the
eventual return value of the primary. This last argument would normally
have the value <code>undef</code>.</p>
<p>The second sequence of handlers would be called <i>after</i> the body of the
primary has executed, but <i>before</i> the return value is returned to the
invoking scope. Once again, each handler would itself be a subroutine,
and each would be called with the same argument list as the primary it
postfixes, plus the &quot;return value(s)&quot; argument ($_[-1]). For a postfix
handlers, this extra argument would hold a reference to an array
containing the value(s) actually returned from its primary.</p>
<p>Normally prefix handlers would be prepended to the appropriate prefix
sequence, whilst postfix handlers would be appended to the appropriate
postfix sequence, thereby preserving the symmetry of pre- and post-fix
handlers. The mechanisms for setting up such sequences are described in
<i><a href='#General Syntax of Handler Installers'>&quot;General Syntax of Handler Installers&quot;</a></i>.</p>
<a name='Prefix Handler Semantics'></a><h2>Prefix Handler Semantics</h2>
<p>A prefix handler may do anything that any other subroutine may do. A
typical action might be to trace or log the invocation of the primary
(the <code>pre</code> syntax is used to set up a handler, and is explained in
<i><a href='#General Syntax of Handler Installers'>&quot;General Syntax of Handler Installers&quot;</a></i>).</p>
<pre>        package Foo;

        # set up a tracing prefix handler for the subroutine &amp;Foo::bar...

        pre bar { 
                local $&quot; = ','
                my @caller = caller;
                print &quot;Called foo with args (@_[0..$#_-1])\n&quot;,
                      &quot;from @caller[1,2]\n&quot;,
                      &quot;in contexts: &quot;, join(&quot;, &quot;,want);
        }</pre>
<p>Note that this (correctly) implies that a handler receives the same
information from <code>caller</code> and <code>want</code> (RFC 21) as its primary would.</p>
<p>However, <code>caller</code> would be extended to return an extra value
when called from a prefix or postfix handler. Specifically, that extra
value would be a reference to the handler's primary. Thus a handler
could detect which primary it is prefixing (or postfixing):</p>
<pre>	sub handler {
		my $primary = (caller(0))[10];
		...
	}</pre>
<p>or (under RFC 259):</p>
<pre>	sub handler {
		my $primary = caller-&gt;{primary};
		...
	}</pre>
<p>Another common usage would be to acquire resources that the primary will use:</p>
<pre>        pre read_file {
                flock $_[0], LOCK_EX;
        }</pre>
<p>(For the obvious complement of this usage, see <i><a href='#Postfix Handler Semantics'>&quot;Postfix Handler Semantics&quot;</a></i>).</p>
<p>Note that, in all cases, the return value of the handler is ignored.</p>
<a name='Special semantics: changes to arguments'></a><h3>Special semantics: changes to arguments</h3>
<p>Each handler receives the same argument list: the list with which the
primary was originally called, plus an extra element representing the
return value.</p>
<p>If a handler changes one of the original arguments -- through one of the
aliases in its @_ array, or by splicing @_ itself -- those changes are
passed on to subsequent handlers and to the primary itself. For example:</p>
<pre>        pre tax_payable_on {
                $_[0] -= 20.00;         # routinely underquote sales price
        }
                

        sub tax_payable_on {            # now sees prices $20 less than
                                        # specified argument
                printf(&quot;Tax: %.2lf&quot;, $_[0] * 0.1);
        }

        $price = 99.95; tax_payable_on($price);  # prints 8.00
        $price = 29.95; tax_payable_on($price);  # prints 0.99
        $price =  9.95; tax_payable_on($price);  # prints -1.01  (a profit!)</pre>
<p>Changes to individual elements of @_ would also be propagated back to the
original argument (as usual).</p>
<p>Note that it would still be possible to set up a handler that changes its
primary's argument list but <i>doesn't</i> propagate the changes back to the
original arguments.</p>
<p>For example, the following prefix handler allows
<code>CORE::open</code> to handle URLs, but <i>changes</i> the second argument:</p>
<pre>        use Regexp::Common;

        pre CORE::open {
                $_[1] = &quot;lynx -source $_[1] |&quot;
                        if $_[1] =~ $RE{URL};
        }</pre>
<p>On the other hand, the following handler does exactly the same thing
<i>without</i> propagating the changed filename back to the original
second argument:</p>
<pre>        pre CORE::open {
                splice @_, 1, 1, &quot;lynx -source $_[1] |&quot;
                        if $_[1] =~ $RE{URL};
        }</pre>
<p>Note that splicing @_ is also the mechanism for altering the <i>number</i>
of arguments passed to the primary. For example, the following
prefix handler changes the semantics of <code>CORE::open</code> when called
with only one argument:</p>
<pre>        pre CORE::open {
                splice @_, $#_, 0, $_
                        if @_ == 2;
        }</pre>
<p>With this handler in effect, a call to <code>open SOMEFILEHANDLE;</code> will look
for the filename in $_ instead of $SOMEFILEHANDLE.</p>
<p>Note that, in the above example, it is important to splice the extra
argument <i>before</i> index $#_ (rather than just pushing the extra
argument onto the end of @_), because the last element of @_ is always
the return value.</p>
<p>The ability to rearrange arguments in this way opens the door to some of
the intriguing possibilities suggested by the Lingua::Romana::Perligata
module. For example, here's how to make <code>bless</code>'s arguments
order-independent:</p>
<pre>        pre CORE::bless {
                splice @_, 0, 2, reverse @_[0..1]
                        if !ref($_[0]) &amp;&amp; ref($_[1]);
        }

        # and later...

        $obj = bless 'ClassName', { attr =&gt; $val };</pre>
<a name='Special semantics: changes to return value slot'></a><h3>Special semantics: changes to return value slot</h3>
<p>If a handler assigns the value to the return value slot,
either explicitly (<code>$_[-1] = $newval</code>) or implicitly
(<code>splice @_, -1, 1, $newval</code>), then the remaining prefix and postfix
handlers are still called, but the primary itself is <i>not</i> called.</p>
<p>Instead, the value in $_[-1] is used as the return value for the primary.
This allows short-circuiting techniques such as memoization to be easily
implemented:</p>
<pre>        my %sin_cache;

        pre CORE::sin {
                $_[-1] = $sin_cache{$_[0]};             # short-circuit
                        if exists $sin_cache{$_[0]}     # if value cached
        }

        post CORE::sin {
                $sin_cache{$_[0]} = $_[-1];             # cache the return val
        }</pre>
<p>This feature might also be used to short-circuit upon failure to acquire
resources:</p>
<pre>        pre read_file {
                flock($_[0], LOCK_EX|LOCK_NB)
                        or $_[-1] = undef;      # Can't lock file so...
                                                # &quot;No data for you!&quot;
        }</pre>
<p>Note that this second example (correctly) implies that short-circuiting
occurs as a result of an <i>assignment</i> to $_[-1], even if that assignment
doesn't change the value of $_[-1].</p>
<a name='Special semantics: exceptions'></a><h3>Special semantics: exceptions</h3>
<p>If a handler throws an exception, that exception is immediately
propagated back to the calling scope, without having invoked any other
handlers (nor the primary itself). This is useful for setting up
preconditions on subroutine and methods (for Design-By-Contact
programming). For example:</p>
<pre>        package PriorityList;

        pre pop {
                my ($self) = @_;
                croak &quot;Can't pop empty PriorityList&quot;
                        unless @{$self-&gt;{list}} &gt; 0;
        }</pre>
<p>An exception might also be an appropriate response
on resource acquisition failure:</p>
<pre>        pre read_file {
                flock($_[0], LOCK_EX|LOCK_NB) or
                        croak &quot;Couldn't get immediate lock&quot;;
        }</pre>
<a name='Postfix Handler Semantics'></a><h2>Postfix Handler Semantics</h2>
<p>When called, a postfix handlers may do anything that any other subroutine
may do. Just like a prefix handler, it may print out tracing information:</p>
<pre>        package Foo;

        post bar { 
                local $&quot; = ','
                my @caller = caller;
                print &quot;Finished call to foo from @caller[1,2]\n&quot;,
                      &quot;returning: @{$_[-1]}&quot;;
        }</pre>
<p>or release resources:</p>
<pre>        post read_file {
                flock $_[0], LOCK_UN;
        }</pre>
<p>or alter the primary's argument list (for example: to effect changes to
the original values after the primary has finished with them):</p>
<pre>        post issue_licence {
                $_[0]--;        # decrement licence counter
                carp &quot;You just used your last licence&quot;
                        if $_[0] == 0;
        }</pre>
<p>or change the return value:</p>
<pre>        post tax_payable_on {
                $_[-1] -= 1.00;         # routinely underquote tax payable
        }
                
        sub tax_payable_on {
                printf(&quot;Tax: %.2lf&quot;, $_[0] * 0.1);
        }

        tax_payable_on(99.95);  # prints 9.00
        tax_payable_on(29.95);  # prints 2.00
        tax_payable_on( 9.95);  # prints -0.01</pre>
<p>or throw an exception (for example, to implement method post-conditions
in a DBC system):</p>
<pre>        package PriorityList;

        post pop {
                my ($self, $return_val) = @_;
                croak &quot;pop returned undef (something odd is happening)&quot;
                        unless defined $return_val;
        }</pre>
<a name='General Syntax of Handler Installers'></a><h2>General Syntax of Handler Installers</h2>
<p>It is proposed that two built-in functions -- <code>pre</code> and <code>post</code> -- be
introduced. These may be used to install prefix or postfix handlers for
any subroutine (or for all subroutines in a single package).
Each would take two arguments:</p>
<ul>
<li><a name='1.'></a>1.</li>
<p>Either a subroutine name (possibly as a bareword),
or a subroutine reference, or a class name (possibly as a bareword).
This argument would be mandatory.</p>
<li><a name='2.'></a>2.</li>
<p>Either a block or subroutine reference implementing the handler,
or a reference to a hash whose single value is a sub reference implementing
the handler, or a string or bareword specifying the logical name of a handler.
This argument would be optional.</p>
</ul>
<p>Thus, in the notation proposed by RFC 128:</p>
<pre>        pre  ( [&quot;&quot;&amp;]identifier; [&quot;&quot;&amp;\%]option)

        post ( [&quot;&quot;&amp;]identifier; [&quot;&quot;&amp;\%]option)</pre>
<p>with all the parsing niceties that implies (e.g. optional barewords in
either position, optional separating comma and optional
terminating semicolon if the second argument is a block, etc.)</p>
<a name='Installing pre Handlers'></a><h2>Installing <code>pre</code> Handlers</h2>
<p>A call to <code>pre</code> would normally install the handler implementation
specified by the second argument) as a prefix handler for the
subroutine specified by the first argument. The handler would be
installed by <i>prepending</i> it to an internal list of handlers for the
subroutine (or package).</p>
<p>Note that <code>pre</code> (and later, <code>post</code>) are <i>not</i> compile-time directives,
but are regular built-in functions that are called as the program executes.
This means that they can be used either to set up handlers during compilation
(e.g. by calling them in the body of a module) or during execution (by
calling them from the main package or from some other subroutine).</p>
<p>If the first argument is a string or bareword, the prefix handler is
installed for the subroutine or method of the same name in the current
package. For example:</p>
<pre>        package Foo;

        pre bar { print &quot;about to bar()...&quot; };</pre>
<p>installs a prefix handler for the subroutine <code>&amp;Foo::bar</code>.</p>
<p>If the specified name is qualified (i.e. contains at least one instance
of &quot;::&quot;), then the handler is installed for the subroutine in the
qualifying package. For example:</p>
<pre>        package Foo;

        pre Coola::bar, sub { print &quot;about to bar()...&quot; };</pre>
<p>installs a prefix handler for the subroutine <code>&amp;Coola::bar</code>.</p>
<p>If the first argument ends in &quot;::&quot; and is therefore the name of a package --
rather than a subroutine -- then the handler is installed in
a special <i>package prefix sequence</i>, and is shared by every
existing (and future) subroutine in the package. For example:</p>
<pre>        pre Cafe::Bar::, sub { print &quot;calling some method of class Cafe::Bar&quot; };</pre>
<p>installs a prefix handler that will be invoked whenever <i>any</i> subroutine
from package Cafe::Bar is called.</p>
<p>If the first argument is a subroutine reference, the handler is installed
for the referent. For example:</p>
<pre>        package Foo;

        pre \&amp;Zan::Zi::bar, sub { print &quot;about to bar()...&quot; };</pre>
<p>installs a prefix handler for the subroutine <code>&amp;Zan::Zi::bar</code>, whilst:</p>
<pre>        package Foo;

        my $anon = sub { print &quot;I am the sub with no name\n&quot; };

        pre $anon, sub { print &quot;about to bar()...&quot; };</pre>
<p>installs a prefix handler for the anonymous subroutine referred to by $anon.</p>
<p>It should be noted that the following two calls are <i>not</i>
identical in their effects:</p>
<pre>        pre &quot;Cross::bar&quot;, sub { print &quot;high jumping...&quot; };
        pre \&amp;Cross::bar, sub { print &quot;high jumping...&quot; };</pre>
<p>For an explanation of the difference between them see, <i><a href='#Inheritance of Handlers'>&quot;Inheritance of Handlers&quot;</a></i>.</p>
<a name='Installing post Handlers'></a><h2>Installing <code>post</code> Handlers</h2>
<p>The semantics of the <code>post</code> function are symmetrical with those
of the <code>pre</code> function described in the previous section.</p>
<p><code>post</code> works in the same way as <code>pre</code> -- with the same semantics for
various forms of the first argument -- except:</p>
<ul>
<li><a name='the handlers it registers are called after the primary returns (instead of before)'></a>the handlers it registers are called <i>after</i> the primary returns
(instead of before)</li>
<li><a name='postfix handlers are called in the same order as they were registered (instead of the reverse order)'></a>postfix handlers are called in the same order as they were registered
(instead of the reverse order)</li>
<li><a name='postfix handlers and package-wide postfix handlers are appended to separate sequences: the postfix sequence and package postfix sequence respectively'></a>postfix handlers and package-wide postfix handlers are appended to
separate sequences: the <code>postfix sequence</code> and <code>package postfix
sequence</code> respectively</li>
</ul>
<a name='Logically Identified Handlers'></a><h2>Logically Identified Handlers</h2>
<p>In order to later manipulate or remove prefix and postfix handlers, it
is convenient to give them a logical name. To this end, the second argument to
<code>pre</code> or <code>post</code> may be specified as reference to a one-element hash:</p>
<pre>        pre Lum::bar, { PAIN =&gt; sub { print &quot;ouch!...&quot; } };
        post Lum::bar, { PAIN =&gt; sub { print &quot;...ahhh!&quot; } };</pre>
<p>These have exactly the same handler-setting effects as:</p>
<pre>        pre Lum::bar, sub { print &quot;ouch!...&quot; };
        post Lum::bar, sub { print &quot;...aaah!&quot; };</pre>
<p>except that the specified handlers now have the logical name &quot;PAIN&quot; associated
with them.</p>
<p>This is important, because at a later point in the code it might be desirable
to replace one or both of the handlers (whilst keeping them
in the same sequential position):</p>
<pre>        pre Lum::bar, { PAIN =&gt; sub { print &quot;OUCH!!!!&quot; } };</pre>
<p>That is, when a handler is re-specified with a logical name, if a
handler of that name already exists in the appropriate prefix or postfix
handler sequence, the new handler replaces the existing one in situ,
rather than being prepended or appended to the handler sequence.</p>
<p>The logical name could also be used to <i>remove</i> the handler
completely:</p>
<pre>        pre Lum::bar, { PAIN =&gt; undef };</pre>
<p>which would delete the named handler from the sequence. A subsequent
<code>pre</code> specification of a handler with the logical name &quot;PAIN&quot; would
therefore <i>prepend</i> the new handler to the prefix sequence (since it no
longer appears within the subroutine's prefix sequence). If the aim is to
remove a named handler, but leave its logical name as a placeholder for
future re-instatement, the following should be used instead:</p>
<pre>        pre Lum::bar, { PAIN =&gt; sub{} };</pre>
<a name='Accessing named handlers'></a><h3>Accessing named handlers</h3>
<p>It is also possible to retrieve a reference to a named handler, by
passing just its logical name as the second argument. For example:</p>
<pre>        $pain_handler = pre Lum::bar, 'PAIN';

        $tree_handler = post \&amp;Coola::bar, 'IS_SHADY';

        $package_handler = pre Cafe::Bar::, 'CHECK_SUGAR';</pre>
<p>Finally, it is possible to retrieve the entire prefix or postfix
handler sequence for a particular subroutine, by passing just its
name/reference to <code>pre</code>:</p>
<pre>        $pain_handler_array_ref = pre Lum::bar;

        $tree_handler_array_ref = post \&amp;Coola::bar;

        $package_handler_array_ref = pre Cafe::Bar::;</pre>
<p>This returns a reference to the actual handler sequence for the
subroutine, in which each element is a reference to a hash whose single
key is the logical name of the handler (or &quot;&quot; if it has no logical name)
and whose single value is a reference to the handler itself. That is, the
structure of the returned value is like this:</p>
<pre>        [
            { 'NAME' =&gt; sub {...} },
            { 'NAME' =&gt; sub {...} },
            { ''     =&gt; sub {...} },
            { 'NAME' =&gt; sub {...} },
            { ''     =&gt; sub {...} },
        ]</pre>
<p>Changes to this array change the actual prefix handling of the corresponding
subroutine.</p>
<p>For example, a particular module might require that any prefix handler
that it installs for <code>&amp;CORE::open</code> (the handler mechanism applies to
built-in functions too) is the very last handler that is called. Hence
the module cannot use:</p>
<pre>        package LastOpen;

        sub import {
                pre CORE::open, \&amp;LastOpen::handler;
        }</pre>
<p>as that would <i>prepend</i> the <code>&amp;LastOpen::handler</code> subroutine to the sequence
of handlers for <code>CORE::open</code>).</p>
<p>Instead, the LastOpen module would use:</p>
<pre>        package LastOpen;

        sub import {
                my $open_prefix_sequence = pre Core::open;
                push @{$open_prefix_sequence}, { &quot;&quot; =&gt; \&amp;LastOpen::handler };
        }</pre>
<p>thereby ensuring the prefix handler is called at the end of <code>CORE::open</code>'s
prefix sequence.</p>
<a name='Inheritance of Handlers'></a><h2>Inheritance of Handlers</h2>
<p><i><a href='http://search.cpan.org/perldoc?Installing <code>pre<#code> Handlers'>&quot;code> Handlers&quot; in Installing <code>pre<</a></i> noted that the following two calls to <code>pre</code>
are not identical in effect:</p>
<pre>        pre \&amp;Cross::bar, sub { print &quot;high jumping...&quot; };
        pre &quot;Cross::bar&quot;, sub { print &quot;high jumping...&quot; };</pre>
<p>The difference between them lies in the way they are treated when the
class Cross is inherited by some other class. For example:</p>
<pre>        package Irate;
        use base 'Cross';

        sub bar { print &quot;humbug!&quot; }</pre>
<p>If a prefix (or postfix) handler for <code>&amp;Cross::bar</code> has been defined via a
direct reference to the subroutine:</p>
<pre>        pre  \&amp;Cross::bar, sub { die if $_[1] &lt; $qualifying_height }
        post \&amp;Cross::bar, sub { die unless $_[0]-&gt;still_balanced() };</pre>
<p>then that handler is <i>not</i> inherited by <code>Irate::bar</code>. Handlers defined
in this way are referred to as being <i>non-heritable</i>.</p>
<p>However, if the handler was defined using a string or bareword representing
<code>&amp;Cross::bar</code>'s name:</p>
<pre>        package Cross;

        pre  bar =&gt; sub { die if $_[1] &lt; $qualifying_height };
        post 'Cross::bar' { die unless $_[0]-&gt;still_balanced() }</pre>
<p>then that handler <i>is</i> inherited by <code>Irate::bar</code>. Hence, handlers
defined in this way are referred to as being <i>heritable</i>.</p>
<p>Heritable handlers are associated with the <i>identifier</i> (i.e. name)
of a particular subroutine, not with its <i>identity</i> (i.e. reference).
Thus it is possible to specify prefix or postfix handlers for a subroutine
that exists <code>in name only</code> within a package. Specifically, it is possible
to associate a heritable handler with a subroutine that is not defined in
a package but is, instead, inherited from some ancestral package.</p>
<a name='Inheritance of postfix handlers'></a><h3>Inheritance of postfix handlers</h3>
<p>Inheritance of postfix handlers is simple. The theory of
Design-By-Contact programming states that heritable postconditions on a
method must be as strong or stronger in a derived class. That is, a
derived-class method may make extra guarantees about its behaviour, but may
never renege on those guarantees already made by its base-class
counterpart.</p>
<p>This implies that any postfix handlers inherited by a derived-class
method act as if they are appended to its heritable postfix sequence, and thus
are called <i>after</i> the derived-class postfix handlers, at which time they
have the opportunity to impose additional constraints on the method.</p>
<p>For example:</p>
<pre>        package Cat;

        sub new { 
                my ($class, $name, $weight) = @_;
                bless { name =&gt; $name, weight =&gt; $weight }, $class;
        }

        post new {
                die &quot;Anti-matter cat detected&quot;
                        if $_[-1]-&gt;{weight} &lt;= 0;
        }

        package Tiger;
        use base 'Cat';

        post new {
                die &quot;Tiger died of shame&quot;
                        if $_[-1]-&gt;{name} eq 'Fluffy';
        }</pre>
<p>Given the above definitions, a Cat object need only have a positive
weight, but a Tiger object must have both a positive weight <i>and</i> an
unembarrassing name.</p>
<p>Note that these same inheritance semantics also apply to package-wide
postcondition handlers (since they are always specified by name, not by
reference). This makes it possible to set up inheritable class invariants.
For example:</p>
<pre>        package Cat;

        pre Cat::, sub { $_[0]-&gt;is_dry() or die &quot;Wet cat :-(&quot; }</pre>
<a name='Inheritance of prefix handlers'></a><h3>Inheritance of prefix handlers</h3>
<p>The inheritance behaviour of prefix handlers is less straightforward.</p>
<p>DBC theory states that the heritable preconditions defined on a
derived-class method must be no stronger (and may well be weaker) than those
for its base-class counterpart. In other words, a derived-class method is
allowed to be more permissive in its requirements, but not more
demanding.</p>
<p>This implies that any heritable prefix handlers inherited from a base
class are executed <i>disjunctively</i> with those heritable handlers
specified in the derived class. In practice this means that the set of
heritable prefix handlers from the base class(es) is invoked within an
<code>eval</code> and if none of them throws an exception, that success suffices
to satisfy the precondition constraint on the method, in which case
the heritable prefix handlers of the derived class are not called
(although the non-heritable handlers are still invoked). If the eval
terminates because some inherited handler threw an exception, then the
full set of prefix handlers (heritable and non-heritable) for the
derived-class are tried instead.</p>
<p>For example, given:</p>
<pre>        package Cat;

        sub new { 
                my ($class, $claw_len, $caged) = @_;
                bless { claw_len =&gt; $claw_len, caged =&gt; $caged }, $class;
        }

        pre new {
                my ($class, $claw_len) = @_;
                die &quot;Too dangerous&quot;
                        if $claw_len &gt; 0.5;
        }

        package Tiger;
        use base 'Cat';

        post new {
                my ($class, $claw_len, $caged) = @_;
                die &quot;Too dangerous&quot;
                        unless $caged;
        }</pre>
<p>then a Cat object must have properly trimmed claws, whereas a Tiger may either
have properly trimmed claws (i.e. the heritable precondition succeeds)
<i>or</i> be safely caged (i.e. the derived precondition succeeds).</p>
<a name='MIGRATION ISSUES'></a><h1>MIGRATION ISSUES</h1>
<p>Minimal. Code with:</p>
<pre>        sub pre { ... }</pre>
<p>and</p>
<pre>        sub post { ... }</pre>
<p>might be affected. Surreptitious name mangling by p52p6
(<code>the_subroutine_formerly_known_as_pre</code>???) would probably solve this
in most cases.</p>
<p>Various modules which provide or make use of mechanisms like this
(e.g. the Hook:: hierarchy, or Memoize)
might like to take advantage of the standardized facility.</p>
<a name='IMPLEMENTATION'></a><h1>IMPLEMENTATION</h1>
<p>A prototype (pure Perl) implementation featuring everything except
package-wide handlers will be available (as the Hook::SubHandlers
module) some time real soon now. It will be archived as:</p>
<pre>        <a href='http://www.csse.monash.edu.au/~damian/CPAN/Hook-SubHandlers.tar.gz' target='_blank'>www.csse.monash.edu.au</a></pre>
<p>and subsequently added to the CPAN.</p>
<p>As Jarrko points out in RFC 194, the implementation details of true built-in
<code>pre</code> and <code>post</code> functions will depend very heavily on what becomes of
typeglobs.</p>
<a name='ACKNOWLEDGEMENTS'></a><h1>ACKNOWLEDGEMENTS</h1>
<p>Thanks to Uri Guttman and Mark-Jason Dominus for their valuable feedback
and suggestions.</p>
<a name='REFERENCES'></a><h1>REFERENCES</h1>
<p>RFC 21: Subroutines: Replace <code>wantarray</code> with a generic <code>want</code> function</p>
<p>RFC 23: Higher order functions</p>
<p>RFC 128: Subroutines: Extend subroutine contexts to include name parameters and lazy arguments</p>
<p>RFC 137: Overview: Perl OO should <i>not</i> be fundamentally changed.</p>
<p>RFC 194: Standardise Function Pre- and Post-Handling</p>
<p>RFC 259: Builtins : Make use of hashref context for garrulous builtins</p>
<p>Meyer, B., &quot;Object Oriented Software Construction, 2nd Edition&quot;, Prentice Hall.</p>
<p>Conway, D., &quot;Lingua::Romana::Perligata -- Perl for the XXI-imus Century&quot;,
Proc.  Perl Conference 4.0, O'Reilly, 2000, pp. 1-16. Also available as:
<a href='http://www.csse.monash.edu.au/~damian/papers/HTML/Perligata.html' target='_blank'>www.csse.monash.edu.au</a></p>
</div>
